package com.zy.explore.db.infrastructure.plugins.multidbsupport.sqlchange.limit;

import com.zy.explore.db.infrastructure.plugins.multidbsupport.sqlchange.base.SqlOper;

import java.util.Collections;
import java.util.List;


public class SqlLimitTest {
    public static void main(String[] args) {
        String sql = "";
        sql += "SELECT CONFIG_VALUE\n";
        sql += "FROM (\n";
        sql += "		(SELECT CONFIG_VALUE, CREATE_DATE AS maxTime\n";
        sql += "			FROM t_appcf_config_sort1\n";
        sql += "			WHERE 1 = 1 AND CREATE_DATE IS NOT NULL ORDER BY CREATE_DATE DESC\n";
        sql += "			LIMIT 10\n";
        sql += "		)\n";
        sql += "		UNION ALL\n";
        sql += "			( SELECT CONFIG_VALUE, UPDATE_DATE AS maxTimeselect\n";
        sql += "				FROM t_appcf_config_sort2\n";
        sql += "				WHERE 1 = 1 AND MODULE_ID = 'SF' AND UPDATE_DATE IS NOT NULL\n";
//		sql += "				ORDER BY UPDATE_DATE DESC\n";
        sql += "				LIMIT 2 , 5 ";
        sql += "			)\n";
        sql += "	) a\n";
        sql += "ORDER BY maxTime DESC\n";
        sql += "LIMIT 3";
        System.out.println(sql);
        System.out.println("===============================");

        List<SqlOper> sqlOperList = SqlLimitUtils.find(sql);

        System.out.println("===============================");

        System.out.println(change(sql, sqlOperList));
    }

    public static String change(String sql, List<SqlOper> sqlOperList) {
        if (sqlOperList.isEmpty()) {
            return sql;
        }
        Collections.sort(sqlOperList);

        StringBuilder sb = new StringBuilder();
        int pre = 0;

        for (SqlOper oper : sqlOperList) {
            int starIdx = oper.getStarIdx();
            if (pre < starIdx) {
                sb.append(sql.substring(pre, starIdx));
                pre = starIdx;
            }

            if (oper.getOper() == SqlOper.OPER_ADD) {
                sb.append(oper.getStr());
            } else if (oper.getOper() == SqlOper.OPER_DELETE) {
                pre = oper.getEndIdx();
            } else if (oper.getOper() == SqlOper.OPER_REPLACE) {
                sb.append(oper.getStr());
                pre = oper.getEndIdx();
            }
        }

        if (pre < sql.length()) {
            sb.append(sql.substring(pre));
        }

        return sb.toString();

    }

}
